package pre.lxm.demo.chart.horizontal;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import pre.lxm.demo.chart.bean.RecordBean;


public class HorizontalRecordChartView extends View {
    private int mWidth, mHeight;
    private int itemHeight;
    private int itemWidth;

    private Paint mPaint;
    private TextPaint mTextPaint;

    private List<RecordBean> mRecordList;
    private int lineHeight;
    private int leftPadding, rightPadding;
    private String[] resultStr = new String[]{"胜", "平", "负"};
    private static final String host = "主";
    private static final String guest = "客";

    public HorizontalRecordChartView(Context context) {
        this(context, null);
    }

    public HorizontalRecordChartView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HorizontalRecordChartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

//    GestureDetector scrollOnListener;

    private void init() {
        itemWidth = getScreenWidth(getContext()) / 8;
        lineHeight = dip2px(1);
        leftPadding = rightPadding = dip2px(16);
        initPaint();
        initTextPaint();
        mRecordList = new ArrayList<>();
//        scrollOnListener = new GestureDetector(getContext(), new ScrollOnListener());

    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setColor(Color.parseColor("#E1E1E1"));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(lineHeight);
    }

    private void initTextPaint() {
        mTextPaint = new TextPaint();
        mTextPaint.setTextSize(sp2px(14));
        mTextPaint.setStrokeWidth(2);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mRecordList.size() == 0) {
            mWidth = getScreenWidth(getContext());
        } else {
//            mWidth = leftPadding + rightPadding + itemWidth * (mRecordList.size() + 1);
//            mWidth = mWidth < getScreenWidth(getContext()) ? getScreenWidth(getContext()) : mWidth;
            mWidth = getScreenWidth(getContext());
        }
        mHeight = getMeasuredHeight();
        itemHeight = (mHeight - lineHeight * 2) / 4;
        setMeasuredDimension(mWidth, getMeasuredHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawCore(canvas);
        drawRecordData(canvas);

    }

    public void refreshData(List<RecordBean> recordList) {
        mRecordList.clear();
        mRecordList.addAll(recordList);
        requestLayout();
        invalidate();
    }

    private void drawCore(Canvas canvas) {

        // 绘制横线
        mPaint.setStrokeWidth(lineHeight);
        mPaint.setColor(Color.parseColor("#E1E1E1"));
        canvas.drawLine(0, lineHeight, mWidth, lineHeight, mPaint);
        canvas.drawLine(0, lineHeight + itemHeight, mWidth, lineHeight + itemHeight, mPaint);

        // 轮次栏底色
        Rect turnRect = new Rect(0, lineHeight, mWidth, lineHeight + itemHeight);
        mPaint.setColor(Color.parseColor("#F5F5F5"));
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawRect(turnRect, mPaint);

        // 轮次
        canvas.save();
        // canvas.translate(leftPadding, 0);
        mTextPaint.setColor(Color.parseColor("#888888"));
        drawText(canvas, mTextPaint, "轮次", leftPadding * 2 + itemWidth, itemHeight);
        canvas.restore();

        // 胜平负底色
        canvas.save();
        canvas.translate(0, itemHeight + lineHeight * 2);
        Rect resultRect = new Rect(0, 0, mWidth, mHeight);
        mPaint.setColor(Color.parseColor("#FFFFFF"));
        canvas.drawRect(resultRect, mPaint);
        canvas.restore();
//
//        // 胜平负
//        canvas.save();
//        mTextPaint.setColor(Color.BLACK);
//        for (int i = 0; i < resultStr.length; i++) {
//            canvas.translate(0, itemHeight + lineHeight * 2);
//            drawText(canvas, mTextPaint, resultStr[i], leftPadding + itemWidth, itemHeight);
//        }
//        canvas.restore();


    }


    private int lastXPos = 0;
    private int movingThisTime;
    private int leftMoving = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
//        return scrollOnListener.onTouchEvent(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastXPos = (int) event.getRawX();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) event.getRawX();
                movingThisTime = lastXPos - moveX;

                Log.e("onTouchEvent", "canRightMove:" + canRightMove + "\tcanLefMove:" + canLeftMove + "\tleftMoving:"
                        + leftMoving);
                lastXPos = moveX;
                Log.e("onTouchEvent", "lastXPos:" + lastXPos + "\tmoveX:" + moveX + "\tmovingThisTime:" +
                        movingThisTime);
                if ((canLeftMove && movingThisTime < 0) || (canRightMove && movingThisTime > 0)) {
                    leftMoving = leftMoving + movingThisTime;
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
//                new Thread(new SmoothScrollThread(movingThisTime)).start();
                break;
        }
        return true;
    }

    private class ScrollOnListener implements GestureDetector.OnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }


        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

            Log.e("onScroll", "distanceX:" + distanceX + "\tdistanceY:" + distanceY);
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }
    }


    private boolean canRightMove = true;
    private boolean canLeftMove = true;

    private void calCanMove() {
        int listSize = mRecordList.size();
        int canShowNum = (mWidth - leftPadding - rightPadding - itemWidth) / itemWidth;
        Log.e("drawRecordData", "---canShowNum---" + canShowNum);
        if (canShowNum >= listSize) {
            canRightMove = false;
            canLeftMove = false;
        } else {
            if ((listSize - canShowNum) * itemWidth <= leftMoving && movingThisTime > 0) {
                //向右滑动但是已经到最后
                Log.e("drawRecordData", "false---canShowNum---" + canShowNum + ";\tleftMoving:" + leftMoving);
                canRightMove = false;
                canLeftMove = true;
            } else if (movingThisTime < 0 && leftMoving <= 0) {
                //向左滑动但是到头
                canLeftMove = false;
                canRightMove = true;
            } else {
                canRightMove = true;
                canLeftMove = true;
            }
        }
    }

    private void drawRecordData(Canvas canvas) {
        if (mRecordList.size() > 0) {
            drawDashLine(canvas);
        }
        calCanMove();
        // 轮次数据
        Log.e("drawRecordData", "leftMoving:" + leftMoving);
        canvas.save();
        canvas.translate(itemWidth + leftPadding, 0);

        Log.e("drawRecordData", "---mWidth---" + mWidth);
        Log.e("drawRecordData", "--x--" + (mWidth - rightPadding - leftPadding - itemWidth));
        for (int i = 0; i < mRecordList.size(); i++) {
            int x = itemWidth + itemWidth * i * 2 - 2 * leftMoving;
            Log.e("drawRecordData", "---x---" + x + "\tleftMoving:" + leftMoving);

            if (x >= 0) {
                drawText(canvas, mTextPaint, mRecordList.get(i).getTurn(), x,
                        itemHeight);
            }
//            canvas.translate(itemWidth, 0);
        }
        canvas.restore();

        // 实线
        drawRealLine(canvas);

        // 客、主
        drawData(canvas);

        // 胜平负底色
        Rect resultRect = new Rect(0, itemHeight + lineHeight * 2, itemWidth + leftPadding,
                mHeight * 3 + itemHeight + lineHeight * 2);
        mPaint.setColor(Color.parseColor("#FFFFFF"));
        canvas.drawRect(resultRect, mPaint);
        // 胜平负
        canvas.save();
        mTextPaint.setColor(Color.BLACK);
        for (int i = 0; i < resultStr.length; i++) {
            canvas.translate(0, itemHeight + lineHeight * 2);
            drawText(canvas, mTextPaint, resultStr[i], leftPadding + itemWidth, itemHeight);
        }
        canvas.restore();

    }

    private void drawData(Canvas canvas) {
        // 客、主
        mTextPaint.setColor(Color.parseColor("#FFFFFF"));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(lineHeight);
        for (int i = 0; i < mRecordList.size(); i++) {
//            canvas.save();
//            canvas.translate(itemWidth * (i + 1) + leftPadding, itemHeight + lineHeight * 2);
            int xPos = itemWidth * (i + 1) + leftPadding;
            int yPos = itemHeight + lineHeight * 2;
            RecordBean itemRecord = mRecordList.get(i);
            String result = itemRecord.getResult();
            String isHost = itemRecord.getIsHost();
            switch (result) {
                case "3":// 胜
                    break;
                case "1":// 平
//                    canvas.translate(0, itemHeight);
                    yPos += itemHeight;
                    break;
                case "0":// 负
                    yPos += itemHeight * 2;
//                    canvas.translate(0, itemHeight * 2);
                    break;
            }
//            canvas.save();
//            canvas.translate(xPos, yPos);
            if (isHost.equals("h")) {
                // mPaint.setStyle(Paint.Style.STROKE);
                Rect mRect = new Rect();
                mTextPaint.getTextBounds(host, 0, host.length(), mRect);
                mPaint.setColor(Color.parseColor("#FF8500"));

                Rect bounds = new Rect(xPos, yPos, xPos + itemWidth, yPos + itemHeight);
                bounds.inset(mRect.width(), mRect.height());
                Rect hostRect = new Rect(bounds.centerX() - mRect.width() * 2 / 3 - leftMoving,
                        bounds.centerY() - mRect.height(),
                        bounds.centerX() + mRect.width() * 2 / 3 - leftMoving,
                        bounds.centerY() + mRect.height());
//                bounds.inset(mRect.width(), mRect.height());
//                canvas.drawCircle(bounds.centerX(), bounds.centerY(), mRect.height(), mPaint);

                canvas.drawRect(hostRect, mPaint);
                Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
                float baseline = itemHeight / 2 + (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics
                        .descent;
                //绘制文字
                canvas.drawText(host, (leftPadding + itemWidth - mRect.width()) / 2 - leftMoving + xPos,
                        yPos + baseline, mTextPaint);

            } else if (isHost.equals("g")) {
                Rect mRect = new Rect();
                mTextPaint.getTextBounds(guest, 0, guest.length(), mRect);

                mPaint.setColor(Color.parseColor("#0081E6"));
                Rect bounds = new Rect(xPos, yPos, xPos + itemWidth, yPos + itemHeight);
                bounds.inset(mRect.width(), mRect.height());
                //绘制边界
                canvas.drawCircle(bounds.centerX() - leftMoving, bounds.centerY(), mRect.height(), mPaint);

                Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
                float baseline = itemHeight / 2 + (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics
                        .descent;
                //绘制文字
                canvas.drawText(guest, (leftPadding + itemWidth - mRect.width()) / 2 - leftMoving + xPos,
                        yPos + baseline, mTextPaint);
            }

        }
    }

    // 实线
    private void drawRealLine(Canvas canvas) {
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(false);
        // mPaint.setStrokeWidth(lineHeight * 2);
        mPaint.setColor(Color.parseColor("#222222"));
        canvas.save();
        canvas.translate(itemWidth + leftPadding, itemHeight + lineHeight * 2);
        for (int i = 0; i < mRecordList.size() - 1; i++) {
            RecordBean curRecord = mRecordList.get(i);
            int curYPoint = 0;
            int nextYPoint = 0;
            int j = i + 1;
            RecordBean nextRecord = mRecordList.get(j);
            switch (curRecord.getResult()) {
                case "3":// 胜
                    curYPoint = itemHeight / 2;
                    break;
                case "1":// 平
                    curYPoint = itemHeight * 3 / 2;
                    break;
                case "0":// 负
                    curYPoint = itemHeight * 5 / 2;
                    break;
            }
            switch (nextRecord.getResult()) {
                case "3":// 胜
                    nextYPoint = itemHeight / 2;
                    break;
                case "1":// 平
                    nextYPoint = itemHeight * 3 / 2;
                    break;
                case "0":// 负
                    nextYPoint = itemHeight * 5 / 2;
                    break;
            }
            canvas.drawLine(itemWidth / 2 + itemWidth * i - leftMoving, curYPoint, itemWidth * 3 / 2 + itemWidth * i
                    - leftMoving, nextYPoint, mPaint);
        }
        canvas.restore();
    }

    //虚线
    private void drawDashLine(Canvas canvas) {
        // 虚线
        canvas.save();
        mPaint.setStrokeWidth(lineHeight);
        canvas.translate(leftPadding + itemWidth, itemHeight + lineHeight * 2);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.parseColor("#CECECE"));
        mPaint.setAntiAlias(true);
        PathEffect pathEffect = new DashPathEffect(new float[]{10, 10, 10, 10}, 1);
        for (int i = 0; i < 3; i++) {
            mPaint.setPathEffect(pathEffect);
            Path path = new Path();
            path.moveTo(20, itemHeight / 2);
            path.lineTo(itemWidth * mRecordList.size() - 20 - leftMoving, itemHeight / 2);
            canvas.drawPath(path, mPaint);
            canvas.translate(0, itemHeight);
        }
        canvas.restore();
    }

    private Rect drawText(Canvas canvas, TextPaint textPaint, String txtString, int txtMeasureWidth,
                          int txtMeasureHeight) {
        Rect mRect = new Rect();
        textPaint.getTextBounds(txtString, 0, txtString.length(), mRect);
        Paint.FontMetricsInt fontMetrics = textPaint.getFontMetricsInt();
        float baseline = txtMeasureHeight / 2 + (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;
        canvas.drawText(txtString, (txtMeasureWidth - mRect.width()) / 2, baseline, textPaint);
        return mRect;
    }

    private int sp2px(float spValue) {
        final float fontScale = getContext().getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    private int dip2px(float dipValue) {
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private static int getScreenWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    private static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    private class SmoothScrollThread implements Runnable {

        float lastMoving;
        boolean scrolling = true;

        private SmoothScrollThread(float lastMoving) {
            this.lastMoving = lastMoving;
            scrolling = true;
        }

        @Override
        public void run() {
            while (scrolling) {
                long start = System.currentTimeMillis();
                lastMoving = (int) (0.9f * lastMoving);
                leftMoving += lastMoving;
                postInvalidate();
                if (Math.abs(lastMoving) < 5) {
                    scrolling = false;
                }
                long end = System.currentTimeMillis();
                if (end - start < 20) {
                    try {
                        Thread.sleep(20 - (end - start));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


}
